import React, { useState, useEffect, useMemo, useLayoutEffect } from 'react';
import { useNavigate, Outlet, useLocation } from "react-router-dom";
import { Menu } from 'antd';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';

import Header from "@/Components/Header/index.jsx";
import './index.scss';

function Home(props) {
  const { t } = useTranslation();
  const version = useSelector(state => state.theme.version);

  const location = useLocation();
  const navigate = useNavigate();

  // 提取菜单配置
  const menuConfig = useMemo(() => [
    { label: t('menu.system'), key: 'system' },
    { label: t('menu.test'), key: 'test' },
    { label: t('menu.config'), key: 'config' },
    { label: t('menu.sensor'), key: 'sensor' },
    { label: t('menu.web'), key: 'web' }
  ], [t]);

  // 从路径中提取当前选中的 key
  const currentKey = location.pathname.split('/').filter(Boolean)[0] || 'system';
  const [sharedData, setSharedData] = useState({});
  const [current, setCurrent] = useState(currentKey);
  const [name, setName] = useState(t('menu.system'));

  // 更新当前选中的菜单项
  useLayoutEffect(() => {
    const pathKey = location.pathname.split('/').filter(Boolean)[0] || 'system';
    const currentItem = menuConfig.find(item => item.key === pathKey);
    setCurrent(pathKey);
    setName(currentItem ? currentItem.label : t('menu.system'));
  }, [location.pathname, menuConfig, t]);

  const onClick = (e) => {
    setCurrent(e.key);
    const selectedItem = menuConfig.find(item => item.key === e.key);
    setName(selectedItem ? selectedItem.label : t('menu.system'));
    navigate(e.key);
  };

  function handleOutletEvent(e) {
    setSharedData(e);
  }

  return (
    <>
      <Header data={sharedData} />
      <div className="navigation">
        <div className="menu">
          <Menu
            onClick={onClick}
            selectedKeys={[current]}
            mode="horizontal"
            items={menuConfig}
          />
        </div>
        <div className="breadcrumb">
          {t('menu.currentLocation')}: {t('menu.home')} {'>'} {name}
        </div>
      </div>
      <main>
        <Outlet context={{ onEvent: handleOutletEvent }} />
        <div className="version">
          {version}
        </div>
      </main>
    </>
  );
}

export default Home;